<template>
  <div class="page art-full-height">
    <Search
      v-show="showSearchBar"
      v-model="searchForm"
      @search="handleSearch"
      @reset="resetSearchParams"
    ></Search>

    <ElCard
      class="art-table-card"
      shadow="never"
      :style="{ 'margin-top': showSearchBar ? '12px' : '0' }"
    >
      <ArtTableHeader
        v-model:columns="columnChecks"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      >
        <template #left>
          <ElSpace wrap style="margin-right: 5px">
            <ElButton v-auth="'common:tables:backup'" @click="backup" v-ripple>备份</ElButton>
            <ElButton v-auth="'common:tables:sql'" @click="showDialog('add')" v-ripple
              >执行SQL语句</ElButton
            >
            <ElButton v-auth="'common:tables:batch'" @click="deleteRole({ type: 2 })" v-ripple
              >删除表</ElButton
            >
            <ElButton v-auth="'common:tables:batch'" @click="deleteRole({ type: 1 })" v-ripple
              >清理表</ElButton
            >
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
      </ArtTable>
    </ElCard>

    <!-- 角色编辑弹窗 -->
    <Dialog
      v-model="dialogVisible"
      :dialog-type="dialogType"
      :role-data="currentData"
      @success="refreshData"
    />
  </div>
</template>

<script setup lang="ts">
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import axios from 'axios'
  import { useTable } from '@/composables/useTable'
  import { fetchTablesList, deleteTablesdApi } from '@/api/tables'
  import { useUserStore } from '@/store/modules/user'
  import Search from './modules/search.vue'
  import Dialog from './modules/dialog.vue'
  import { ElMessageBox, ElButton, ElTooltip } from 'element-plus'
  import { useAuth } from '@/composables/useAuth'
  const { hasAuth } = useAuth()

  // 选中行
  const selectedRows = ref<any[]>([])
  // 搜索表单
  const searchForm = ref({
    search: undefined
  })

  const showSearchBar = ref(false)

  const dialogVisible = ref(false)
  const currentData = ref<any | undefined>(undefined)
  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    // 核心配置
    core: {
      apiFn: fetchTablesList,
      apiParams: {
        current: 1,
        size: 20
      },
      // 排除 apiParams 中的属性
      excludeParams: ['daterange'],
      columnsFactory: () => [
        { type: 'selection' }, // 勾选列
        { type: 'index', width: 60, label: '序号' }, // 序号
        {
          prop: 'Name',
          label: '表名称',
          minWidth: 150
        },
        {
          prop: 'Comment',
          label: '表注释',
          minWidth: 150
        },
        {
          prop: 'Engine',
          label: '表引擎',
          minWidth: 80
        },
        {
          prop: 'Collation',
          label: '字符集',
          minWidth: 170
        },
        {
          prop: 'Rows',
          label: '总行数',
          minWidth: 90
        },
        {
          prop: 'Data_length_mb',
          label: '数据(MB)',
          minWidth: 90
        },
        {
          prop: 'Create_time',
          label: '创建日期',
          width: 180,
          sortable: true
        },
        {
          prop: 'operation',
          label: '操作',
          width: 140,
          fixed: 'right', // 固定列
          formatter: (row) => {
            return h('div', { style: 'text-align: right' }, [
              hasAuth('common:tables:batch') &&
                h(
                  ElTooltip,
                  { content: '清理', placement: 'top' },
                  {
                    default: () =>
                      h(ArtButtonTable, {
                        type: 'view',
                        onClick: () =>
                          deleteRole({ ...(row && typeof row === 'object' ? row : {}), type: 1 })
                      })
                  }
                ),
              hasAuth('common:tables:batch') &&
                h(
                  ElTooltip,
                  { content: '删除', placement: 'top' },
                  {
                    default: () =>
                      h(ArtButtonTable, {
                        type: 'delete',
                        onClick: () =>
                          deleteRole({ ...(row && typeof row === 'object' ? row : {}), type: 2 })
                      })
                  }
                )
            ])
          }
        }
      ]
    }
  })
  const dialogType = ref<'add' | 'edit'>('add')

  const showDialog = (type: 'add' | 'edit', row?: any) => {
    dialogVisible.value = true
    dialogType.value = type
    currentData.value = row
  }

  /**
   * 搜索处理
   * @param params 搜索参数
   */
  const handleSearch = (params: Record<string, any>) => {
    // 处理日期区间参数，把 daterange 转换为 startTime 和 endTime
    const { daterange, ...filtersParams } = params
    const [startTime, endTime] = Array.isArray(daterange) ? daterange : [null, null]

    // 搜索参数赋值
    Object.assign(searchParams, { ...filtersParams, startTime, endTime })
    getData()
  }
  /**
   * 备份表
   */
  const { accessToken } = useUserStore()
  const backup = async () => {
    try {
      ElMessage.success('备份中,请稍候...')
      const apiUrl = import.meta.env.VITE_API_URL
      const response = await axios.get(`${apiUrl}/common.tables/backup`, {
        responseType: 'blob',
        headers: {
          Authorization: `Bearer ${accessToken}` // 如需鉴权
        }
      })
      const blob = response.data
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', `backup_${new Date().toISOString()}.sql`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      ElMessage.success('备份成功，下载完毕')
    } catch {
      ElMessage.error('备份失败，请稍后重试')
    }
  }
  /**
   * type: 2 删除表 1 清理表
   */
  const typeMap: Record<string, { label: string; api: typeof deleteTablesdApi }> = {
    '2': { label: '删除', api: deleteTablesdApi },
    '1': { label: '清理', api: deleteTablesdApi }
  }

  const deleteRole = (payload?: { type: number; Name?: string }) => {
    const type = payload?.type || 1
    const action = typeMap[String(type)]?.label || '操作'
    // 单条操作
    if (payload && payload.Name) {
      ElMessageBox.confirm(`确定要${action}【${payload.Name}】吗？`, `${action}`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: type === 1 ? 'error' : 'warning'
      }).then(async () => {
        if (payload.Name) {
          await typeMap[String(type)].api({ ids: [payload.Name], type })
        }
        ElMessage.success(`${action}成功`)
        getData()
      })
      return
    }
    // 批量操作
    if (!selectedRows.value.length) {
      ElMessage.warning('请先勾选要操作的数据')
      return
    }
    ElMessageBox.confirm(
      `确定要${action}选中的${selectedRows.value.length}个数据吗？`,
      `批量${action}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: type === 1 ? 'error' : 'warning'
      }
    ).then(async () => {
      const names = selectedRows.value.map((item) => item.Name)
      await typeMap[String(type)].api({ ids: names, type })
      ElMessage.success(`批量${action}成功`)
      getData()
    })
  }
  /**
   * 处理表格行选择变化
   */
  const handleSelectionChange = (selection: any[]): void => {
    selectedRows.value = selection
    console.log('选中行数据:', selectedRows.value)
  }
</script>

<style lang="scss" scoped>
  .page {
    padding-bottom: 15px;
  }
</style>
